package com.showtao.front.service;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;

import javax.servlet.ServletContext;
import javax.transaction.Transactional;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ServletContextAware;

import com.showtao.common.constant.ApplicationConstant;
import com.showtao.common.enumeration.EErrorCode;
import com.showtao.common.exception.BizServiceException;
import com.showtao.front.domain.Resource;
import com.showtao.front.repository.ResourceRepository;

@Service
public class ResourceService implements ServletContextAware {

	private ServletContext sc;
	@Autowired
	private ResourceRepository resourceRepository;
	@Autowired
	private UploadedFileHandler uploadedFileHandler;
	
	@Transactional
	public Resource saveResource(Resource resource){
		return resourceRepository.save(resource);
	}
	
	@Transactional
	public Resource saveFromResId(String resId){
		if(StringUtils.isBlank(resId)){
			throw new BizServiceException(EErrorCode.COMM_INTERNAL_ERROR, "ResId cannot be blank");
		}
		Resource entity = null;
		if(resId.indexOf(ApplicationConstant.UPLOAD_TEMP_URI)!=-1){
			try{
				String tempDir = sc.getRealPath(ApplicationConstant.UPLOAD_TEMP_FOLDER);
				File file = new File(tempDir + '/' + FilenameUtils.getName(resId));
				String resourceId = uploadedFileHandler.put(file);
				entity = new Resource();
				entity.setCreatedAt(Calendar.getInstance().getTime());
				entity.setResId(resourceId);
				entity.setExt(FilenameUtils.getExtension(resId));
				entity = resourceRepository.save(entity);
				return entity;
			}catch(IOException e){
				throw new BizServiceException(EErrorCode.COMM_INTERNAL_ERROR, e.getMessage());
			}
		}else{
			entity = resourceRepository.getByResId(resId);
		}
		
		return entity;
	}

	@Override
	public void setServletContext(ServletContext sc) {
		this.sc = sc;
	}
}
